<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资讯ID" prop="articleId">
        <el-input
          v-model="queryParams.articleId"
          placeholder="请输入资讯ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-select v-model="queryParams.language" placeholder="请选择语言" clearable>
          <el-option label="中文" value="cn" />
          <el-option label="英文" value="en" />
        </el-select>
      </el-form-item>
      <el-form-item label="TTS引擎" prop="ttsEngine">
        <el-input
          v-model="queryParams.ttsEngine"
          placeholder="请输入TTS引擎"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tzai:audio:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tzai:audio:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tzai:audio:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="audioList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="音频ID" align="center" prop="audioId" width="80" />
      <el-table-column label="资讯ID" align="center" prop="articleId" width="80" />
      <el-table-column label="语言" align="center" prop="language" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.language === 'cn'" type="success">中文</el-tag>
          <el-tag v-else-if="scope.row.language === 'en'" type="primary">英文</el-tag>
          <el-tag v-else type="info">{{ scope.row.language }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="音频地址" align="center" prop="audioUrl" :show-overflow-tooltip="true" width="200">
        <template slot-scope="scope">
          <el-link v-if="scope.row.audioId" @click="handleView(scope.row)" type="primary">
            <i class="el-icon-headset"></i> 查看
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="时长(秒)" align="center" prop="duration" width="100" />
      <el-table-column label="TTS引擎" align="center" prop="ttsEngine" width="120" />
      <el-table-column label="音色" align="center" prop="voiceName" width="120" />
      <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handlePlay(scope.row)"
            style="color: #67C23A;"
          >播放</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tzai:audio:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tzai:audio:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改音频文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="资讯ID" prop="articleId">
          <el-input v-model="form.articleId" placeholder="请输入资讯ID" />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-select v-model="form.language" placeholder="请选择语言">
            <el-option label="中文" value="cn" />
            <el-option label="英文" value="en" />
          </el-select>
        </el-form-item>
        <el-form-item label="音频地址" prop="audioUrl">
          <el-input v-model="form.audioUrl" placeholder="请输入音频地址" />
        </el-form-item>
        <el-form-item label="时长(秒)" prop="duration">
          <el-input-number v-model="form.duration" :min="0" :precision="2" placeholder="请输入时长" />
        </el-form-item>
        <el-form-item label="时间戳" prop="timestamps">
          <el-input v-model="form.timestamps" type="textarea" :rows="5" placeholder="请输入时间戳(JSON格式)" />
        </el-form-item>
        <el-form-item label="TTS引擎" prop="ttsEngine">
          <el-input v-model="form.ttsEngine" placeholder="请输入TTS引擎" />
        </el-form-item>
        <el-form-item label="音色名称" prop="voiceName">
          <el-input v-model="form.voiceName" placeholder="请输入音色名称" />
        </el-form-item>
        <el-form-item label="文件大小" prop="fileSize">
          <el-input-number v-model="form.fileSize" :min="0" placeholder="请输入文件大小(字节)" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 音频播放对话框 -->
    <el-dialog title="音频播放" :visible.sync="playOpen" width="600px" append-to-body @close="closeAudioPlayer">
      <div style="text-align: center;">
        <audio v-if="currentAudioUrl" :src="currentAudioUrl" controls autoplay style="width: 100%;"></audio>
        <p style="margin-top: 20px; color: #909399;">{{ currentAudioInfo }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAudio, getAudio, delAudio, addAudio, updateAudio, playAudio, downloadAudio } from "@/api/tzai/audio";

export default {
  name: "Audio",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 音频文件表格数据
      audioList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 播放对话框
      playOpen: false,
      // 当前播放音频地址
      currentAudioUrl: "",
      // 当前播放音频信息
      currentAudioInfo: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        articleId: null,
        language: null,
        audioUrl: null,
        duration: null,
        timestamps: null,
        ttsEngine: null,
        voiceName: null,
        fileSize: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        articleId: [
          { required: true, message: "资讯ID不能为空", trigger: "blur" }
        ],
        language: [
          { required: true, message: "语言不能为空", trigger: "change" }
        ],
        audioUrl: [
          { required: true, message: "音频地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询音频文件列表 */
    getList() {
      this.loading = true;
      listAudio(this.queryParams).then(response => {
        this.audioList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        audioId: null,
        articleId: null,
        language: null,
        audioUrl: null,
        duration: null,
        timestamps: null,
        ttsEngine: null,
        voiceName: null,
        fileSize: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.audioId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加音频文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const audioId = row.audioId || this.ids
      getAudio(audioId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改音频文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.audioId != null) {
            updateAudio(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAudio(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const audioIds = row.audioId || this.ids;
      this.$modal.confirm('是否确认删除音频文件编号为"' + audioIds + '"的数据项？').then(function() {
        return delAudio(audioIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tzai/audio/export', {
        ...this.queryParams
      }, `audio_${new Date().getTime()}.xlsx`)
    },
    /** 查看音频（打开播放对话框） */
    handleView(row) {
      this.handlePlay(row);
    },
    /** 播放音频 */
    handlePlay(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载音频...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 使用API方法获取音频（携带token）
      playAudio(row.audioId).then(response => {
        loading.close();
        
        // 创建Blob URL
        const blob = new Blob([response], { type: 'audio/mpeg' });
        const blobUrl = window.URL.createObjectURL(blob);
        
        // 设置播放信息
        this.currentAudioUrl = blobUrl;
        this.currentAudioInfo = `语言: ${row.language === 'cn' ? '中文' : '英文'} | TTS引擎: ${row.ttsEngine || '-'} | 音色: ${row.voiceName || '-'} | 时长: ${row.duration || 0}秒`;
        this.playOpen = true;
      }).catch(error => {
        loading.close();
        this.$modal.msgError("音频加载失败，请稍后重试");
        console.error('播放音频失败:', error);
      });
    },
    /** 下载音频 */
    handleDownload(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在下载音频...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 使用API方法下载文件（携带token）
      downloadAudio(row.audioId).then(response => {
        loading.close();
        
        // 创建Blob URL并触发下载
        const blob = new Blob([response], { type: 'application/octet-stream' });
        const blobUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = `audio_${row.articleId}_${row.language}.mp3`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
        
        this.$modal.msgSuccess("音频下载成功");
      }).catch(error => {
        loading.close();
        this.$modal.msgError("音频下载失败，请稍后重试");
        console.error('下载音频失败:', error);
      });
    },
    /** 关闭音频播放器并清理资源 */
    closeAudioPlayer() {
      if (this.currentAudioUrl && this.currentAudioUrl.startsWith('blob:')) {
        window.URL.revokeObjectURL(this.currentAudioUrl);
      }
      this.currentAudioUrl = '';
      this.currentAudioInfo = '';
    },
    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '-';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
    }
  }
};
</script>
